package com.ckjava.test.aop;

import com.ckjava.xutils.Constants;
import com.ckjava.xutils.StringUtils;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

public abstract class AopBase implements Constants {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 日志拦截
     */
    @Pointcut("execution(public * com.ckjava.test.web.*Controller.*(..))")
    public void controllerPointCut(){}

    /**
     * 处理响应
     * @param response
     * @param obj
     */
    public void processResponse(HttpServletResponse response, Object obj) {
        response.setContentType("application/json;charset=UTF-8");
        ObjectMapper mapper = new ObjectMapper();
        mapper.setTimeZone(TimeZone.getTimeZone("GMT+08"));
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        try {
            mapper.writeValue(response.getWriter(), obj);
        } catch (IOException e) {
            logger.error("AopOpLog processResponse has error", e);
        }
    }

    /**
     * 获取客户端真正IP
     * @param request
     * @return
     */
    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}
